import { Service } from "egg";

class UserService extends Service {
  /**
   * 用户登录
   * @param param
   */
  public async login(param: any) {
    try {
      const result: any = await this.ctx.model.User.findOne({
        attributes: ["user_id"],
        where: {
          user_name: param.user_name,
          user_password: param.user_password
        }
      });
      if (!result) {
        throw new Error(JSON.stringify({ code: 2, msg: "登录失败" }));
      }
      return result;
    } catch (e) {
      this.ctx.logger.error(e);
      throw new Error(e.message);
    }
  }

  /**
   * 用户注册
   * @param param
   */
  public async register(param: any) {
    try {
      const user = await this.ctx.model.User.findOne({
        attributes: ["user_id"],
        where: {
          user_name: param.user_name
        }
      });
      if (user) {
        throw new Error(JSON.stringify({ code: 2, msg: "该用户名已被注册！" }));
      }
      param.user_id = this.ctx.helper.genUUID();
      param.user_sex = "1";
      param.user_age = 24;
      const result = await this.ctx.model.User.create(param);
      if (!result) {
        throw new Error(JSON.stringify({ code: 2, msg: "注册失败" }));
      }
    } catch (e) {
      this.ctx.logger.error(e);
      throw new Error(e.message);
    }
  }
}

export default UserService;
